package _08_DFS_BFS;

public class _695_岛屿的最大面积 {

    public static void main(String[] args) {
        _695_岛屿的最大面积 v = new _695_岛屿的最大面积();

        int[][] ins = new int[][]{
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
                {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
        };
        System.out.println(v.maxAreaOfIsland(ins));
    }

    public int maxAreaOfIsland(int[][] grid) {
        // 记录岛屿的最大面积
        int max = 0;
        // 记录边界条件
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 0) continue;
                // 陆地，深度优先搜索，岛屿最大面积
                max = Math.max(max, dfs(grid, i, j));
            }
        }
        return max;
    }

    private int dfs(int[][] grid, int row, int col) {
        if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] == 0) {
            return 0;
        }
        // 记录当前岛屿被访问过
        grid[row][col] = 0;
        int count = 1;
        // 上
        count += dfs(grid, row - 1, col);
        // 下
        count += dfs(grid, row + 1, col);
        // 左
        count += dfs(grid, row, col - 1);
        // 右
        count += dfs(grid, row, col + 1);
        return count;
    }

}
